package com.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
//初始化
class InitChannel extends ChannelInitializer {

    @Override
    protected void initChannel(Channel channel) throws Exception {
          channel.pipeline().addLast(new StringEncoder());
          channel.pipeline().addLast(new StringDecoder());
          channel.pipeline().addLast(new RecvServerMessage());
    }
}

//监听收到消息
class RecvServerMessage extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        System.out.println("收到服务器传过来的消息:"+msg);
    }
}


public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //1.客户端装配器
        Bootstrap bootstrap = new Bootstrap();
        //2.事件组
        EventLoopGroup workGroup = new NioEventLoopGroup();
        bootstrap.group(workGroup);
        //3.设置通道类型
        bootstrap.channel(NioSocketChannel.class);
        //4.事件
        bootstrap.handler(new InitChannel());
        //5.连接服务器,并发送到服务器
        ChannelFuture cf =  bootstrap.connect("192.168.0.200",9090).sync();
        cf.channel().writeAndFlush("Hello,我是客户端");
        //6.关闭
        cf.channel().closeFuture().sync();
        System.out.println("关闭了");
        //7.关闭事件组
        workGroup.shutdownGracefully();

    }
}
